package com.sdx.coop.exam.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.CoreDictBusinessService;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.coop.exam.entity.ExamPapers;
import com.sdx.coop.exam.service.ExamPapersService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;



/**
 * 试卷 接口
 */
@RequestMapping("/coop/examPapers")
@Controller
public class ExamPapersController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(ExamPapersController.class);
    private static final String MODEL = "/coop/examPapers";


    @Resource
	private ExamPapersService examPapersService;
    
    @Resource
	private ResCloudFileService resCloudFileService;

    @Resource
    private CoreDictBusinessService coreDictBusinessService;

	/**
	 * 初始化页面需要的列表数据，
	 * @param view
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
		view.addObject("subjectIdList",coreDictBusinessService.getSubjects());
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("coop.examPapers.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("coop.examPapers.edit")
    @ResponseBody
    public ModelAndView edit(String examId,HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        ExamPapers examPapers = examPapersService.queryById(examId);
        view.addObject("examPapers", examPapers);
	    setPageParam(view,request);
		try {
			view.addObject("examPapersJson", JacksonUtils.toJsonString(examPapers,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("coop.examPapers.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
	    setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("coop.examPapers.query")
    @ResponseBody
    public JsonResult<PageQuery> list(ExamPapers condtion)
    {
    	if(StringUtils.isNotEmpty(condtion.getExamTitle())) {
    		condtion.setExamTitle("%"+condtion.getExamTitle()+"%");
	    }
        PageQuery page = condtion.getPageQuery();
        examPapersService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,ExamPapers examPapers,HttpServletRequest request
							,MultipartFile examUrlFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/coop/exampapers/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(examUrlFile)) {
			try
			{
		        String examUrlFileNamePair = FileUtils.upload(subPath,examUrlFile);
		        String examUrlStoreFile = examUrlFileNamePair.split("::")[0];
				String examUrlUrl = ConfigService.fileUrl+"/exampapers/"+dir+"/"+examUrlStoreFile;
				examPapers.setExamUrl(examUrlUrl);
		        examUrlStoreFile = subPath+examUrlStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+examUrlStoreFile,bucketName,examUrlStoreFile.substring(1));
				resCloudFileService.insertResFile(ResCloudFile.ALI,examUrlStoreFile,examUrlUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);

    	if (isNew) {
    		examPapers.setExamId(Utils.uuid());
			examPapers.setCreatedBy(user.getId().intValue());
			examPapers.setCreatedName(user.getName());
			examPapers.setCreatedTime(new Date());
			examPapers.setUpdatedBy(user.getId().intValue());
			examPapers.setUpdatedName(user.getName());
			examPapers.setUpdatedTime(new Date());
			examPapersService.save(examPapers);
		} else {
			examPapers.setUpdatedBy(user.getId().intValue());
			examPapers.setUpdatedName(user.getName());
			examPapers.setUpdatedTime(new Date());
			examPapersService.updateTemplate(examPapers);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("coop.examPapers.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)ExamPapers examPapers,HttpServletRequest request
							,@RequestParam("examUrlFile") MultipartFile examUrlFile
		)
    {

        return save(true,examPapers,request
					,examUrlFile
		);
    }

    @PostMapping("/update.json")
    @Function("coop.examPapers.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  ExamPapers examPapers,HttpServletRequest request
							,@RequestParam("examUrlFile") MultipartFile examUrlFile) {
		return save(false,examPapers,request
		,examUrlFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("coop.examPapers.query")
    @ResponseBody
    public JsonResult<ExamPapers>queryInfo(String examId) {
        ExamPapers examPapers = examPapersService.queryById( examId);
        return  JsonResult.success(examPapers);
    }

    @PostMapping("/delete.json")
    @Function("coop.examPapers.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        examPapersService.batchDelExamPapers(idList);
        return JsonResult.success();
    }


    

}
